<?php

namespace app\mobileapp\controller;

use \think\Db;

class Order extends Base
{
    /**
     * User: Simony
     * Function:创建订单
     */
    public function createRechargeOrder()
    {
        $memberId = $this->memberId;
        $options_id = input('options_id/d', 0);
        $scene = input('scene/d', 0);
        if (!in_array($scene, [1, 2, 3])) $this->api_ajaxReturn(ERROR, '充值场景必须时支付宝或者微信');


        $rechargeOptionsModel = model('common/member/RechargeOptions');
        $rechargeOptions = $rechargeOptionsModel->getInfoByID($options_id, 'price,money');
        if (empty($rechargeOptions)) $this->api_ajaxReturn(ERROR, '充值选项不存在');

        $price = $rechargeOptions['price'];
        if ($price <= 0) $this->api_ajaxReturn(ERROR, '选项金额异常');

        $order_sn = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        $add_log_data = [
            'member_id' => $memberId,
            'money' => $rechargeOptions['money'],
            'price' => $rechargeOptions['price'],
            'order_sn' => $order_sn,
            'recharge_type' => $scene,
            'create_time' => time(),
        ];

        Db::startTrans();
        $rechargeLogModel = model('common/member/RechargeLog');
        $add_log_res = $rechargeLogModel->add($add_log_data);
        if (!$add_log_res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '订单创建失败');
        }

        $data = [];
        switch ($scene) {
            case 1:
                $appWxPayLogic = model('common/appWxPayLogic', 'logic');
                $res = $appWxPayLogic->unifiedorder($order_sn, '充值', $price, 'haode123-1213');
                if ($res['code'] != SUCCESS) {
                    Db::rollback();
                    $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
                }
                $data = $res['result'];
                break;
            case 2:
                $appAliPayLogic = model('common/AppAliPayLogic', 'logic');
                $res = $appAliPayLogic->unifiedorder($order_sn, '充值', $price, 'haode123-1213');

                if ($res['code'] != SUCCESS) {
                    Db::rollback();
                    $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
                }
                $data = $res['result'];
                break;
            case 3:
                $res = [
                    'code' => SUCCESS,
                    'msg' => '成功',
                ];
                $data = [];
                break;
        }

        $data = array_merge(['order_sn' => $order_sn], $data);
        Db::commit();

        $this->api_ajaxReturn($res['code'], $res['msg'], $data);
    }

    /**
     * User: Simony
     * Function:查看充值订单
     */
    public function queryRechargeOrder()
    {
        $memberId = $this->memberId;
        $order_sn = input('order_sn/s', '');

        $rechargeLogModel = model('common/member/RechargeLog');

        //数据库查
        $where = ['member_id' => $memberId, 'order_sn' => $order_sn];
        $rechargeLog = $rechargeLogModel->getInfo($where, 'money,order_sn,recharge_type,state');

        empty($rechargeLog) && $this->api_ajaxReturn(ERROR, '订单不存在');
        $rechargeLog = $rechargeLog->toArray();

        $data = [];
        if ($rechargeLog['recharge_type'] == 1) {
            //微信查
            $appWxPayLogic = model('common/appWxPayLogic', 'logic');
            $res = $appWxPayLogic->queryOrder($order_sn);
            if ($res['code'] == ERROR) $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
            $data = $res['result'];
        } elseif ($rechargeLog['recharge_type'] == 2) { //支付宝

            $appAliPayLogic = model('common/AppAliPayLogic', 'logic');
            $res = $appAliPayLogic->queryOrder($order_sn);
            if ($res['code'] == ERROR) $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
            $data = $res['result'];
        } else {
            $this->api_ajaxReturn(ERROR, '错误的支付类型');
        }


        $data = array_merge($rechargeLog, $data);

        $this->api_ajaxReturn($res['code'], $res['msg'], $data);
    }

    /**
     * @api {POST} mobileapp/Order/wxNotifyUrl 接受微信异步通知
     * @apiVersion 0.1.0
     * @apiGroup 订单模块
     */
    public function wxNotifyUrl()
    {

        //param
        $appWxPayLogic = model('common/appWxPayLogic', 'logic');

        $postXml = file_get_contents("php://input");
        $param = $appWxPayLogic->xmlToArr($postXml);

        if (!($param['return_code'] == "SUCCESS" && $param['result_code'] == "SUCCESS")) return; //支付不成功

        //回调校验
        $check = $appWxPayLogic->notifyCheck($param);
        if (!$check) return;

        $rechargeLogModel = model('common/member/RechargeLog');
        $where = ['order_sn' => $param['out_trade_no'], 'state' => 0];
        $rechargeLog = $rechargeLogModel->getInfo($where);

        if (empty($rechargeLog)) return;

        if ($param['total_fee'] != intval($rechargeLog['price'] * 100)) return; //金额对不上

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($rechargeLog['member_id']);
        if (empty($member)) return;


        $updata_data = [
            'state' => 1,
            'pay_time' => $param['time_end'],
        ];
        Db::startTrans();
        $edit_res = $rechargeLogModel->edit($where, $updata_data);
        if (!$edit_res) {
            Db::rollback();
            return;
        }

        $desc = '会员充值';
        $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member['id'], $rechargeLog['money'], 1, 1, $desc);
        if ($update_available_balance_res['code'] != SUCCESS) {
            Db::rollback();
            return;
        }

        Db::commit();
        $xml_arr = [
            'return_code' => 'SUCCESS',
            'return_msg' => 'OK',
        ];
        $reply = $appWxPayLogic->arrToXml($xml_arr);
        echo $reply;

    }

    /**
     * @api {POST} mobileapp/Order/alipayNotifyUrl 接受支付宝异步通知
     * @apiVersion 0.1.0
     * @apiGroup 订单模块
     */
    public function alipayNotifyUrl()
    {
        $param = input('param.');

        $appAliPayLogic = model('common/AppAliPayLogic', 'logic');

        //回调校验
        $check = $appAliPayLogic->notifyCheck($param);

        if (!$check) return 'fail';

        if ($param['trade_status'] != 'TRADE_SUCCESS') return; //非支付成功

        $rechargeLogModel = model('common/member/RechargeLog');
        $where = ['order_sn' => $param['out_trade_no'], 'state' => 0];
        $rechargeLog = $rechargeLogModel->getInfo($where);
        if (empty($rechargeLog)) return 'fail';

        if (floatval($param['total_amount']) != floatval($rechargeLog['price'])) return 'fail';

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($rechargeLog['member_id']);
        if (empty($member)) return 'fail';

        $updata_data = [
            'state' => 1,
            'pay_time' => strtotime($param['gmt_payment']),
        ];
        Db::startTrans();
        $edit_res = $rechargeLogModel->edit($where, $updata_data);
        if (!$edit_res) {
            Db::rollback();
            return 'fail';
        }

        $desc = '会员充值';
        $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member['id'], $rechargeLog['money'], 1, 1, $desc);
        if ($update_available_balance_res['code'] != SUCCESS) {
            Db::rollback();
            return 'fail';
        }

        Db::commit();
        echo 'success';
    }


    /**
     * @api {POST} mobileapp/Order/applePayNotifyUrl 接受支付宝异步通知
     * @apiVersion 0.1.0
     * @apiGroup 订单模块
     */
    public function applePayNotifyUrl()
    {
        $memberId = $this->memberId;

        $receipt_data = input('post.receipt_data', '');
        $transaction_id = input('post.transaction_id');
        $order_sn = input('post.order_sn');

        if (empty($receipt_data) || empty($transaction_id) || empty($order_sn)) $this->api_ajaxReturn(ERROR, '参数有误');

        $rechargeLogModel = model('common/member/RechargeLog');
        $where = ['order_sn' => [$transaction_id, $order_sn], 'member_id' => $memberId];
        $rechargeLog = $rechargeLogModel->getInfo($where);

        if (empty($rechargeLog)) $this->api_ajaxReturn(ERROR, '订单不存在');
        if ($rechargeLog['state'] == 1) $this->api_ajaxReturn(ERROR, '订单已支付');

        //验证
        $validate_pay_res = model('common/AppApplePayLogic', 'logic')->validatePay($receipt_data, true);
        if ($validate_pay_res['code'] != SUCCESS) $this->api_ajaxReturn($validate_pay_res['code'], $validate_pay_res['msg'], $validate_pay_res['result']);

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($rechargeLog['member_id']);
        if (empty($member)) $this->api_ajaxReturn(ERROR, '订单已支付');


        $updata_data = [
            'order_sn' => $transaction_id,
            'state' => 1,
            'pay_time' => $validate_pay_res['result']['receipt']['in_app'][0]['purchase_date_ms'] / 1000, //这里用读取的时间
        ];

        Db::startTrans();
        $edit_res = $rechargeLogModel->editByID($rechargeLog['id'], $updata_data);
        if (!$edit_res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '更新订单失败');
        }

        $desc = '会员充值';
        $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($member['id'], $rechargeLog['money'], 1, 1, $desc);
        if ($update_available_balance_res['code'] != SUCCESS) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '更新会员余额失败');
        }

        Db::commit();
        $this->api_ajaxReturn(SUCCESS, '支付成功');

    }

}
